<template>
	<view class="step_e_row">
		<view class="title"> 你希望多久可以达成目标 </view>
		<view class="date_picker_view">
			<picker-view :value="value" @change="bindChange" class="picker-view">
				<picker-view-column>
					<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
				</picker-view-column>
			</picker-view>
		</view>
		<view class="week_num">
			需要约
			<p>{{weeksToSelectedDate || '--'}}</p>周
		</view>
		<!-- 	<view class="train_info" v-if="trainTotalDay > 0 || unTrainTotalDay > 0">
			<view class="info_item">
				<text class="label">训练天数：</text>
				<text class="value">{{trainTotalDay}}天</text>
			</view>
			<view class="info_item">
				<text class="label">休息天数：</text>
				<text class="value">{{unTrainTotalDay}}天</text>
			</view>
			<view class="info_item">
				<text class="label">总计天数：</text>
				<text class="value">{{trainTotalDay + unTrainTotalDay + 1}}天</text>
			</view>
		</view> -->
	</view>
</template>

<script>
	export default {
		props: {
			trainTotalDay: {
				type: Number,
				default: 0
			},
			unTrainTotalDay: {
				type: Number,
				default: 0
			}
		},
		data() {
			const today = new Date();
			const currentYear = today.getFullYear();
			const currentMonth = today.getMonth() + 1;
			const currentDay = today.getDate();

			// 生成从当前年份到未来 5 年的年份数组
			const years = [];
			for (let i = currentYear; i <= currentYear + 5; i++) {
				years.push(i);
			}

			// 计算明天的日期
			const tomorrow = new Date(today);
			tomorrow.setDate(tomorrow.getDate() + 1);
			const tomorrowYear = tomorrow.getFullYear();
			const tomorrowMonth = tomorrow.getMonth() + 1;
			const tomorrowDay = tomorrow.getDate();

			return {
				title: 'picker-view',
				years,
				year: tomorrowYear,
				months: [],
				month: tomorrowMonth,
				days: [],
				day: tomorrowDay,
				// 初始化选择值为明天的日期对应的索引
				value: [
					years.indexOf(tomorrowYear),
					0,
					0
				],
				visible: true,
				indicatorStyle: `height: 50px;`,
				currentYear,
				currentMonth,
				currentDay,
				weeksToSelectedDate: '', // 新增公共变量，初始为空字符串
				selectedDate: null, // 存储选择的日期
				isAutoUpdating: false // 标记是否正在自动更新日期
			};
		},
		watch: {
			// 监听训练天数和休息天数的变化
			trainTotalDay: {
				handler(newVal, oldVal) {
					this.updateDateBasedOnTrainingDays();
				}
			},
			unTrainTotalDay: {
				handler(newVal, oldVal) {
					this.updateDateBasedOnTrainingDays();
				}
			}
		},
		created() {
			this.updateMonthsAndDays();
		},
		methods: {
			// 根据训练天数和休息天数更新日期
			updateDateBasedOnTrainingDays() {
				// 如果两个值都有效且不是正在自动更新中
				if ((this.trainTotalDay > 0 || this.unTrainTotalDay > 0) && !this.isAutoUpdating) {
					this.isAutoUpdating = true;

					// 计算总天数（训练天数 + 休息天数 + 1）
					const totalDays = this.trainTotalDay + this.unTrainTotalDay + 1;

					// 获取当前日期
					const today = new Date();

					// 计算新的目标日期
					const targetDate = new Date(today);
					targetDate.setDate(today.getDate() + totalDays);

					// 更新年月日
					this.year = targetDate.getFullYear();
					this.month = targetDate.getMonth() + 1;
					this.day = targetDate.getDate();

					// 更新月份和日期数组
					this.updateMonthsAndDays();

					// 计算周数
					this.calculateWeeksToSelectedDate();

					// 重置自动更新标记
					this.$nextTick(() => {
						this.isAutoUpdating = false;
					});
				}
			},
			// 点击选择日期
			bindChange(e) {
				// 如果是自动更新中，不处理用户操作
				if (this.isAutoUpdating) return;

				const val = e.detail.value;
				this.year = this.years[val[0]];
				this.month = this.months[val[1]];
				this.day = this.days[val[2]];
				this.updateMonthsAndDays();
				this.calculateWeeksToSelectedDate();
			},
			updateMonthsAndDays() {
				const months = [];
				const days = [];

				// 生成月份数组
				if (this.year === this.currentYear) {
					for (let month = this.currentMonth; month <= 12; month++) {
						months.push(month);
					}
				} else {
					for (let month = 1; month <= 12; month++) {
						months.push(month);
					}
				}

				// 生成当前选择月份的日期数组
				const daysInMonth = new Date(this.year, this.month, 0).getDate();
				if (this.year === this.currentYear && this.month === this.currentMonth) {
					for (let day = this.currentDay + 1; day <= daysInMonth; day++) {
						days.push(day);
					}
				} else {
					for (let day = 1; day <= daysInMonth; day++) {
						days.push(day);
					}
				}

				this.months = months;
				this.days = days;

				// 确保年份索引不被错误更新
				const yearIndex = this.years.indexOf(this.year);
				const monthIndex = this.months.indexOf(this.month);
				const dayIndex = this.days.indexOf(this.day);

				// 防止索引越界
				const safeYearIndex = yearIndex >= 0 ? yearIndex : 0;
				const safeMonthIndex = monthIndex >= 0 ? monthIndex : 0;
				const safeDayIndex = dayIndex >= 0 ? dayIndex : 0;

				this.value = [safeYearIndex, safeMonthIndex, safeDayIndex];
			},
			calculateWeeksToSelectedDate() {
				const today = new Date();
				const selectedDate = new Date(this.year, this.month - 1, this.day);
				this.selectedDate = selectedDate;
				const timeDifference = selectedDate - today;
				const daysDifference = timeDifference / (1000 * 60 * 60 * 24);
				let weeksDifference = daysDifference / 7;

				if (weeksDifference > 0) {
					weeksDifference = Math.ceil(weeksDifference);
				}

				this.weeksToSelectedDate = weeksDifference;
			},
			// 获取表单数据
			getFormData() {
				const formattedYear = String(this.year).padStart(2, '0');
				const formattedMonth = String(this.month).padStart(2, '0');
				const formattedDay = String(this.day).padStart(2, '0');
				return {
					deadLine: `${formattedYear}-${formattedMonth}-${formattedDay}T14:30:00`
					// deadline: Date.now()
				};
			},
			validateForm() {
				return true
			}
		}
	};
</script>

<style lang="less">
	.picker-view {
		width: 750rpx;
		height: 400rpx;
		margin-top: 20rpx;
		background-color: #f9f8fc;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}


	.step_e_row {
		.title {
			font-size: 40rpx;
			font-weight: 600;
			margin: 60rpx 0;
			margin-top: 0;
			color: #000;
		}

		.week_num {
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: 600;
			font-size: 32rpx;
			margin-top: 42rpx;

			p {
				font-size: 28rpx;
				margin: 0 10rpx;
				padding: 5rpx 10rpx;
				background-color: rgba(110, 88, 170, 0.2);
				color: rgba(110, 88, 170, 1);
				border-radius: 10rpx;
			}
		}

	}
</style>